<!-- 编辑弹窗 -->
<template>
  <el-dialog v-if="visible" :destroy-on-close="true" :lock-scroll="false"  :title="isUpdate?'修改客户':'添加客户'"
             :visible="visible" custom-class="ele-dialog-form" width="750px" @update:visible="updateVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" @keyup.enter.native="save"
             @submit.native.prevent>
      <el-form-item label="客户编号:">
        <span v-if="form.customer_number">{{ form.customer_number }}</span>
        <span v-else>自动生成</span>
      </el-form-item>

      <el-form-item label="客户名称:" prop="name">
        <el-input :maxlength="100" v-model="form.name" clearable placeholder="请输入客户名称"/>
      </el-form-item>

      <el-form-item label="客户简称:" prop="short_name">
        <el-input :maxlength="100" v-model="form.short_name" clearable placeholder="请输入客户简称"/>
      </el-form-item>

      <el-form-item label="客户类型:" prop="entry_type_name">
        <el-select v-model="form.entry_type_name" class="ele-block" clearable placeholder="请选择客户类型">
          <el-option v-for="(item, index) in entry_type_nameList" :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域:" prop="city">
        <div class="area">
          <City @areaChange="areaChange" :ids="cityName"/>
        </div>
      </el-form-item>

      <el-form-item label="详细地址:" prop="address">
        <el-input :maxlength="200" v-model="form.address" clearable placeholder="请输入详细地址"/>
      </el-form-item>
      <el-form-item label="所属行业:" prop="industry_name">
        <el-select v-model="form.industry_name" class="ele-block" clearable placeholder="请选择所属行业">
          <el-option v-for="(item, index) in industry_nameList" :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>

      <el-form-item label="客户性质:" >
        <el-select v-model="form.customer_type_name" class="ele-block" clearable placeholder="请选择客户性质">
          <el-option v-for="(item, index) in customer_type_nameList" :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户标签:" >
        <el-radio-group v-model="form.tag_name" class="c-label">
          <el-radio-button v-for="(item, index) in tag_nameList" :key="index" :label="item" :value="item"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="安全等级:">
        <el-select v-model="form.safe_level" class="ele-block" clearable placeholder="请选择安全等级">
          <el-option v-for="(item, index) in safe_levelList" :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>

      <el-form-item label="客户来源:" >
        <el-select v-model="form.source" class="ele-block" clearable placeholder="请选择客户来源">
          <el-option v-for="(item, index) in sourceList" :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>

      <el-form-item label="客户负责人:" prop="owner_name">
        <el-autocomplete v-model="form.owner_name" :fetch-suggestions="querySearchAsync" class="w-full"
                         placeholder="搜索负责人" value-key="nickname" @select="handleSelect"></el-autocomplete>
      </el-form-item>

      <el-form-item label="上级单位:" prop="parent_name">
        <el-autocomplete v-model="form.parent.name" :fetch-suggestions="querySearchAsyncParentUnit" class="w-full"
                         placeholder="搜索上级单位" value-key="name" @select="handleSelectParentUnit"></el-autocomplete>
      </el-form-item>

      <el-form-item label="签约日期" prop="contact_at">
        <el-date-picker v-model="form.contact_at" format="yyyy-MM-dd" placeholder="选择日期" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import  City from '@/components/city'
export default {
  name: 'CityEdit',
  components:{
    City
  },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    // 全部城市数据
    deptList: Array
  },
  data() {
    const validateAreas = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.city.length) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    return {
      //省市区名字
      cityName:"",
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      //客户来源数组
      sourceList: [],
      //客户类型数组
      entry_type_nameList: [],
      //所属行业数组
      industry_nameList: [],
      //客户性质数组
      customer_type_nameList: [],
      //客户标签数组
      tag_nameList: [],
      //安全等级数组
      safe_levelList: [],
      //客户标签
      tagsList: [],
      rules: {
        name: [
          {required: true, message: "请输入客户名称", trigger: "blur"}
        ],
        short_name: [
          {required: true, message: "请输入客户简称", trigger: "blur"}
        ],
        contact_at: [
          {required: true, message: "请选择签约时间", trigger: "change"}
        ],
        entry_type_name: [
          {required: true, message: "请选择客户类型", trigger: "change"}
        ],

        industry_name: [
          {required: true, message: "请选择所属行业", trigger: "change"}
        ],
        city: [
          {required: true, trigger: "change", validator: validateAreas}
        ],
        address: [
          {required: true, message: "请输入详细地址", trigger: "blur"}
        ],
        owner_name: [
          {required: true, message: "请选择客户负责人", trigger: "change"}
        ],
      },
      //表单数组配置项
      dataList: [],
      // 表单数据
      form: {parent:null},
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },
  watch: {
    data() {
      this.isUpdate = !!(this.data && this.data.id);
      this.form = this.initFormData(this.data);
      this.isUpdate&&this.data ? this.city = [this.data.province_id,this.data.city_id,this.data.county_id]:[]
      this.isUpdate&&this.data?this.cityName=this.data.province_name+'/'+this.data.city_name+'/'+this.data.county_name:''
      if(!this.isUpdate){
        this.cityName=''
      }
    }
  },
  mounted() {
    this.form.parent={}
    this.initCustomersParams()
  },
  methods: {
    areaChange(val){
      this.city = val
    },
    //初始化客户参数
    initCustomersParams() {
      this.$http.get(`/customers/params`).then((res) => {
        this.entry_type_nameList = res.data.data.types
        this.industry_nameList = res.data.data.industries
        this.customer_type_nameList = res.data.data.properties
        this.safe_levelList = res.data.data.levels
        this.sourceList = res.data.data.sources
        this.tag_nameList=res.data.data.tags
      })
    },
    //远程搜索获取上级单位
    querySearchAsyncParentUnit(query, cb) {
      query = query ? query : ''
      this.$http.get(`/customers?limit=10&keyword=${query} `).then((res) => {
        cb(res.data.data.filter(item => {
          return item.id !== this.form.parent_id
        }));
      });
    },
    //选择上级单位
    handleSelectParentUnit(val) {
      this.form.parent_id = val.id
    },
    querySearchAsync(query, cb) {
      query = query ? query : ''
      this.$http.get(`/user/index?limit=10&realname=${query} `).then((res) => {
        cb(res.data.data.filter(item => {
          return item.id !== 1
        }));
      });
    },
    handleSelect(item) {
      this.form.owner_id = item.id;
    },
    /* 刷新表格 */
    reload() {
      this.$refs.table?.reload({where: this.where});
    },
    //获取deptList
    // getDeptList() {
    //   const loading = this.$loading({lock: true});
    //   this.$http.get('/dept/index').then(res => {
    //     loading.close();
    //     if (res.data.code === 0) {
    //       this.deptLists = res.data.data.filter(item => {
    //         if (item.type === 3) {
    //           return item
    //         }
    //       })
    //       this.reload();
    //     } else {
    //       this.$message.error(res.data.msg);
    //     }
    //   }).catch(e => {
    //     loading.close();
    //     this.$message.error(e.message);
    //   });
    // },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form = Object.assign({}, this.form, {
            province_id: this.city[0],
            city_id: this.city[1],
            county_id: this.city[2]
          });
          this.loading = true;
          if (this.isUpdate) {
            this.$http.put(`/customers/${this.data.id}`,
              Object.assign({}, this.form, {
                pid: this.form.pid || 0
              })
            ).then(res => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                this.updateVisible(false);
                this.form = {parent: {}}
                this.$emit('done');
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(e => {
              this.loading = false;
              this.$message.error(e.message);
            });
          } else {
            this.$http.post(`/customers`,
              Object.assign({}, this.form, {
                pid: this.form.pid || 0
              })
            ).then(res => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                this.updateVisible(false);
                this.$emit('done');
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(e => {
              this.loading = false;
              this.$message.error(e.message);
            });
          }

        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      if (!this.isUpdate) {
        this.form = {parent: {}}
        this.city=[]
        this.form.parent_id=''
      }
      this.$emit('update:visible', value);
    },
    /* 初始化form数据 */
    initFormData(data) {
      // 初始化默认值
      let form = {level: 1};
      if (data) {
        this.city = [data.province_id, data.city_id, data.county_id]
        Object.assign(form, data);
      }
      if(form.parent==null){
        form.parent={}
      }
      return form;
    },
  }
}
</script>

<style scoped>
.area /deep/.el-cascader{
  width: 100%;
}
.el-autocomplete {
  width: 100%;
}

.el-input {
  width: 100% !important;
}
</style>
